package com.epro.dx.activity.filter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.task.GetOneKeyFilterSettingsAsyncTask;
import com.epro.dx.task.GetTopCategoryAsyncTask;
import com.epro.dx.task.SaveOneKeyFilterSettingsAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.flowlayout.FlowLayout;
import com.epro.dx.widget.flowlayout.TagAdapter;
import com.epro.dx.widget.flowlayout.TagFlowLayout;
import com.epro.dx.widget.flowlayout.TagFlowLayout.OnTagClickListener;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.OneKeyFilterResponseModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.StringUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/************************
 * @author Tony
 * @Date:2016-3-24上午10:41:32
 * @描述: 品类过滤选择页面
 ************************/
public class CategoryFilterActivity extends BaseFragmentActivity implements OnClickListener {
	
	private ArrayList<CatelogModel> whiteCategorys = new ArrayList<CatelogModel>();
	private ArrayList<CatelogModel> blackCategorys = new ArrayList<CatelogModel>();
	private TagFlowLayout myFlowlayoutUp;
	private TagFlowLayout myFlowlayoutDown;
	private TagAdapter<CatelogModel> tagAdapter;
	private TagAdapter<CatelogModel> d_tagAdapter;
	private TextView topbarDone;
	private ImageButton showAllDepartmentsbtn;//显示所有－按钮
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sendScreen();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_category_filter);
		//设置标题
		setTitleContent(R.string.page_title_filter_category);
		setLeftBtnContent(true, -1);
		getDatasFromIntent();
		
		myFlowlayoutUp = (TagFlowLayout) findViewById(R.id.filter_flowlayout_up);
		myFlowlayoutDown = (TagFlowLayout) findViewById(R.id.filter_flowlayout_down);
		topbarDone = (TextView) findViewById(R.id.btn_topbar_done);
		showAllDepartmentsbtn = (ImageButton) findViewById(R.id.filter_flowlayout_btn_show_all_departments);
		
		topbarDone.setOnClickListener(this);
		showAllDepartmentsbtn.setOnClickListener(this);
		
		tagAdapter = new TagAdapter<CatelogModel>(whiteCategorys) {

			@Override
			public View getView(FlowLayout parent, int position, CatelogModel t) {
				RelativeLayout flowTextLayout = (RelativeLayout)LayoutInflater.from(CategoryFilterActivity.this).inflate(R.layout.flow_text,myFlowlayoutUp, false);
				TextView tv = (TextView) flowTextLayout.findViewById(R.id.flow_text_text);
				ImageView deletex = (ImageView) flowTextLayout.findViewById(R.id.flow_text_img);
				deletex.setVisibility(View.VISIBLE);
				tv.setText(t.getShortName());
				return flowTextLayout;
			}
		};
		d_tagAdapter = new TagAdapter<CatelogModel>(blackCategorys) {

			@Override
			public View getView(FlowLayout parent, int position, CatelogModel t) {
				RelativeLayout flowTextLayout = (RelativeLayout)LayoutInflater.from(CategoryFilterActivity.this).inflate(R.layout.flow_text,myFlowlayoutDown, false);
				TextView tv = (TextView) flowTextLayout.findViewById(R.id.flow_text_text);
				ImageView deletex = (ImageView) flowTextLayout.findViewById(R.id.flow_text_img);
				deletex.setVisibility(View.INVISIBLE);
				tv.setText(t.getShortName());
				return flowTextLayout;
			}
		};
		
		myFlowlayoutUp.setAdapter(tagAdapter);
		myFlowlayoutDown.setAdapter(d_tagAdapter);
		myFlowlayoutUp.setOnTagClickListener(new OnTagClickListener() {
			
			@Override
			public boolean onTagClick(View view, int position, FlowLayout parent) {
				if(whiteCategorys.size()<=3){//白名单不能小于3个，给出提示
					showToast(CategoryFilterActivity.this.getString(R.string.whitecategory_at_least_size_notice));
				}else{
					blackCategorys.add(whiteCategorys.get(position));
					whiteCategorys.remove(position);
					startAimation(view,false);
				}
				return true;
			}
		});
		myFlowlayoutDown.setOnTagClickListener(new OnTagClickListener() {
			
			@Override
			public boolean onTagClick(View view, int position, FlowLayout parent) {
				whiteCategorys.add(blackCategorys.get(position));
				blackCategorys.remove(position);
				startAimation(view,true);
				return true;
			}
		});
		if(ActivityUtil.isLogin(CategoryFilterActivity.this)){
			getDataFromOnline();
		}
	}
	
	
	/**
	 * @创建：Tony 2016-4-6下午2:44:03
	 * @描述：请求服务器获取最新数据
	 */
	private void getDataFromOnline() {
		AsyncTaskUtil.executeTask(new GetOneKeyFilterSettingsAsyncTask(CategoryFilterActivity.this, new MyAsyncTaskListenner() {
			
			@Override
			public void onPreTask() {
			}
			
			@Override
			public void onPostTask(String result, Object obj) {
				if("0".equals(result) && !isFinishing()){
					if(null!=obj){
						OneKeyFilterResponseModel model = (OneKeyFilterResponseModel)obj;
						List<CatelogModel> whiteCategoryData = model.getWhiteCategoryData();
						if(null!=whiteCategoryData && whiteCategoryData.size()>0){
							//只有白名单不为空的时候才进行下一步操作
							whiteCategorys.clear();
							blackCategorys.clear();
							whiteCategorys.addAll(whiteCategoryData);
							List<CatelogModel> blackCategoryData = model.getBlackCategoryData();
							if(null!=blackCategoryData && blackCategoryData.size()>0){
								blackCategorys.addAll(blackCategoryData);
							}
							tagAdapter.notifyDataChanged();
							d_tagAdapter.notifyDataChanged();
						}
					}
				}
			}
		}));
	}


	/**
	 * @创建：Tony 2016-3-31下午6:05:15
	 * @描述：获取上个页面穿过来的数据
	 */
	private void getDatasFromIntent() {
		Intent intent = getIntent();
		if(null!=intent){
			Bundle bundleExtra = intent.getBundleExtra(ServerConstant.OneKeyFilter.FILTERBUNDLE);
			if(null!=bundleExtra){
				ArrayList<CatelogModel> whiteList = bundleExtra.getParcelableArrayList(ServerConstant.OneKeyFilter.WHITECATEGORY);
				if(null!=whiteList && whiteList.size()>0){
					whiteCategorys.addAll(whiteList);
				}
				ArrayList<CatelogModel> blackList=bundleExtra.getParcelableArrayList(ServerConstant.OneKeyFilter.BLACKCATEGORY);
				if(null!=blackList && blackList.size()>0){
					blackCategorys.addAll(blackList);
				}
			}
		}
		
	}


	/**
	 * 开启选择品类动画
	 * @param v
	 * @param fromLocation
	 * @param toLocation
	 */
	@SuppressLint("NewApi")
	public void startAimation(View v,final boolean isToUp){
		ScaleAnimation ta = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		ta.setBackgroundColor(Color.TRANSPARENT);
		ta.setDuration(200);
		ta.setFillAfter(true);
		
		final ScaleAnimation sa = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		sa.setBackgroundColor(Color.TRANSPARENT);
		sa.setDuration(200);
		sa.setFillAfter(true);
		
		ta.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation arg0) {
				
			}
			
			@Override
			public void onAnimationRepeat(Animation arg0) {
				
			}
			
			@Override
			public void onAnimationEnd(Animation arg0) {
				tagAdapter.notifyDataChanged();
				d_tagAdapter.notifyDataChanged();
				if(isToUp){
					if(myFlowlayoutUp.getChildCount()>0){
						myFlowlayoutUp.getChildAt(myFlowlayoutUp.getChildCount()-1).startAnimation(sa);
					}
					
				}else{
					if(myFlowlayoutDown.getChildCount()>0){
						myFlowlayoutDown.getChildAt(myFlowlayoutDown.getChildCount()-1).startAnimation(sa);
					}
				}
			}
		});
		v.startAnimation(ta);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_topbar_done://保存设置
			sendGAEvent("点击保存按钮");
			String blackCategoryIds = getBlackCategoryIds();
			AsyncTaskUtil.executeTask(new SaveOneKeyFilterSettingsAsyncTask(CategoryFilterActivity.this, OnekeyFilterLocalUtil.getFilterState(CategoryFilterActivity.this), blackCategoryIds,blackCategorys,whiteCategorys, new MyAsyncTaskListenner() {
				
				@Override
				public void onPreTask() {
//					showWaitingDialog();
					showLoadingLayout(null);
				}
				
				@Override
				public void onPostTask(String result, Object obj) {
//					hideWaitingDialog();
					hideAllLayout();
					if("0".equals(result)){
						//添加返回上个页面返回的参数
						Intent intent = new Intent();
						Bundle bundle = new Bundle();
						bundle.putParcelableArrayList(ServerConstant.OneKeyFilter.WHITECATEGORY, whiteCategorys);
						bundle.putParcelableArrayList(ServerConstant.OneKeyFilter.BLACKCATEGORY, blackCategorys);
						intent.putExtra(ServerConstant.OneKeyFilter.FILTERBUNDLE, bundle);
						setResult(0, intent);
						//更新一级品类本地数据库
						AsyncTaskUtil.executeTask(new GetTopCategoryAsyncTask(CategoryFilterActivity.this, null));
						StringUtil.saveConfig("Home_RefreshBFD", "true");
						finish();
					}else{
						AlertToast.alert(CategoryFilterActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
					}
				}
			}));
			break;
		case R.id.filter_flowlayout_btn_show_all_departments://将所有分类置为白名单
			sendGAEvent("点击显示所有品类按钮");
			if(null!=blackCategorys && blackCategorys.size()>0){
				whiteCategorys.addAll(blackCategorys);
				blackCategorys.clear();
				tagAdapter.notifyDataChanged();
				d_tagAdapter.notifyDataChanged();
			}
			break;
		default:
			break;
		}
	}


	/**
	 * @创建：Tony 2016-4-1下午1:40:25
	 * @描述：拼接参数：黑名单分类ID
	 */
	private String getBlackCategoryIds() {
		StringBuilder sb = new StringBuilder();
		if(null!=blackCategorys && blackCategorys.size()>0){
			for(int i =0;i<blackCategorys.size();i++){
				if(i==blackCategorys.size()-1){
					sb.append(blackCategorys.get(i).getBrowseID());
				}else{
					sb.append(blackCategorys.get(i).getBrowseID()+"-");
				}
			}
		}
		return sb.toString();
	}
}
